package com.sakiko.audiobook.user.factory.impl;

import com.sakiko.audiobook.user.factory.StrategyFactory;
import com.sakiko.audiobook.user.strategy.ItemTypeStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author: sakiko
 * time: 2025/11/9 0:44
 * description: 1001=AlbumStrategy; 1002=TrackStrategy; 1003=vipStrategy
 * ============================================================================
 * 当用@Autowired注入Map<String, ItemTypeStrategy>时，Spring会自动收集所有ItemTypeStrategy接口的实现类Bean，
 */
@Service
public class StrategyFactoryImpl implements StrategyFactory {

    // 如何处理？
    /**
     * 将IOC容器中 ItemTypeStrategy接口下所有实现类对象注入到 Map中
     * Map中 Key: Bean对象ID
     * Map中 Value: 实现类对象
     * {"1001":购买类型为专辑策略类对象}
     * {"1002":购买类型为声音策略类对象}
     * {"1003":购买类型为会员策略类对象}
     */
    @Autowired // 使用 @Autowired注入 map，自动收集 value泛型对应的实现类
    private Map<String, ItemTypeStrategy> strategyMap;
    // 另一种注入方式
//    private final Map<String, ItemTypeStrategy> strategyMap;
//
//    public StrategyFactoryImpl(Map<String, ItemTypeStrategy> strategyMap) {
//        this.strategyMap = strategyMap;
//    }

    @Override
    public ItemTypeStrategy getStrategy(String type) {
        // 1001=AlbumStrategy; 1002=TrackStrategy; 1003=vipStrategy
        if (strategyMap.containsKey(type)) {
            return strategyMap.get(type);
        }
        // 默认返回空
        return null;
    }
}
